<template>
    <div class="notice">
          <div class="search">
            关键字：
            <el-input
              style="width: 195px; padding-right:10px"
              placeholder="请输入标题/内容/发布人"
              prefix-icon="el-icon-search"
              v-model="searchData.keyword">
            </el-input>
      
            发布范围：
            <el-select style="width: 180px;" v-model="searchData.receiverIds" placeholder="请输入发布范围">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>

              <div class="block" style="display: inline; margin-left: 15px">
                <span class="demonstration">发布日期：</span>
                <el-date-picker
                  v-model="timeDate"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleTimeChange">
                </el-date-picker>
              </div>
      
            <el-button style=" float: right; margin-left:10px;" @click="reset">重置</el-button>
            <el-button style=" float: right;" type="primary" @click="onSubmit">查询</el-button>
          </div>
      
          <div class="do">
            <el-button style="margin-left:10px;" @click="dialogFormVisible()">新增</el-button>
            <el-button @click="batchDelete()">批量删除</el-button>
          </div>

          <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题">
          </el-table-column>

          <el-table-column label="内容">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="width: 400px">
                  <mavon-editor v-model="scope.row.content" :subfield="false" :default-open="'preview'" :toolbars-flag="false" :editable="false"/>
                </div>
                <span>{{ stripMarkdown(scope.row.content) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>


          <el-table-column
            prop="publishUsername"
            label="发布人">
          </el-table-column>
          <el-table-column
            prop="receivers"
            label="发布范围">
            <template #default="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.receivers.join(',')" placement="top">
                <span>{{ String(scope.row.receivers.join(',')).length > 10? String(scope.row.receivers.join(',')).substring(0, 10) + '......' : scope.row.receivers.join(',') }}</span>
              </el-tooltip>
            </template>
          </el-table-column>              
          <el-table-column
            prop="status"
            label="标签"
            :filters="[{ text: '待发布', value: 0 }, { text: '已发布', value: 1 },{ text: '作废', value: 2 }]"
            :filter-method="filterTag"
            filter-placement="bottom-end">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '待发布' ? 'primary' : 'success'"
                disable-transitions>{{getStatusText(scope.row.status)}}</el-tag>
            </template>
          </el-table-column>          
          <el-table-column
          label="发布日期"
          >
          <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.publishTime }}</span>
          </template>
          </el-table-column>
          <el-table-column label="操作">
          <template slot-scope="scope">
              <el-button v-if="scope.row.status !== 2"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              <el-button
              size="mini"
              type="warning"
              v-if="scope.row.status !== 2"
              @click="handleCancel(scope.$index, scope.row)">作废</el-button>
          </template>
          </el-table-column>
      </el-table>

      <div class="block" style="text-align: right; padding-top: 10px; background-color: #fff;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </div>

      <NotickForm :visible.sync='visible' @updateFormData="handleUpdateData" :formData="updateTableData" :title.sync="title"></NotickForm>
    </div>
  </template>
  
  <script>
  import { mavonEditor } from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'
  import NotickForm from './NotickFormPop.vue';
  import api from '@/api';

  export default {
      components: {
        NotickForm,
        mavonEditor
      },
      data() {
        return {
          currentPage: 1,
          total:100,
          pageSize:10,
          timeDate:[],
          visible: false,
          selectedRow:[],
          title: '新增公告',
          tableData: [{
            id: '',
            publishTime: '2016-05-02',
            status: 1,
            title: '小区公共设施维修通知',
            publishUserId: '',
            publishUsername: '超级管理员',
            content:"尊敬的业主：小区将于2023年7月15日-7月20日对公共设施进行维修，期间可能会影响部分区域的正常使用，请业主们合理安排出行，给您带来的不便敬请谅解。",
            receivers:['状元楼-一单元','状元楼-二单元']
          },{
            id: '',
            publishTime: '2016-05-02',
            status: 0,
            title: '小区公共设施维修通知',
            publishUserId: '',
            publishUsername: '超级管理员',
            content:"尊敬的业主：小区将于2023年7月15日-7月20日对公共设施进行维修，期间可能会影响部分区域的正常使用，请业主们合理安排出行，给您带来的不便敬请谅解。",
            receivers:['状元楼-一单元','状元楼-二单元']
          }],
          updateTableData:{
            id: '',
            publishTime: null,
            status: 0,
            title: '',
            publishUserId: '',
            publishUsername: '',
            content:"",
            receivers:[]
          },
          searchData:{
            keyword: '',
            receiverIds: '',
            startTime: '',
            endTime: '',
            pageNow: 1,
          },
          options:[]
        }
      },
      methods: {
          stripMarkdown(text) {
            if (!text) return '';

            // 使用 mavonEditor 解析 Markdown
            const html = mavonEditor.getMarkdownIt().render(text);

            // 去掉HTML标签
            const plainText = html.replace(/<[^>]*>/g, '');

            // 截取前 10 个字符
            return plainText.length > 10 ? plainText.substring(0, 10) + '...' : plainText;
          },        
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
          this.searchData.pageNow = val
          //获取公告信息
          this.onSubmit();
        },
        handleTimeChange(){
            this.searchData.startTime = this.timeDate[0],
            this.searchData.endTime = this.timeDate[1]
        },
        // 重置
        reset(){
            this.searchData.keyword = '',
            this.searchData.receiverIds = ''
            this.timeDate = []
        },
        // 查询
        onSubmit(){
          api.noticeList(this.searchData).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                  let noticeInfoDTO = res.data.data.noticeInfoDTO;
                  // 将 options 数组转换为以 value 为键、label 为值的对象
                  const optionsMap = this.options.reduce((map, option) => {
                      map[option.value] = option.label;
                      return map;
                  }, {});
                  noticeInfoDTO.forEach(item => {
                      if (item.receiverIds) {
                          // 处理 receiverIds 字符串为数组
                          const receiverIds = item.receiverIds.split(',').map(id => id.trim());
                          // 使用 map 方法和 optionsMap 构建 receivers 数组
                          const receivers = receiverIds.map(id => optionsMap[id]).filter(label => label);
                          item.receivers = receivers;
                      }
                  });
                  this.tableData = noticeInfoDTO;
                  this.total = res.data.data.total
              }else{
                this.$message.error(res.data.message)
              }
          })
        },
         // 新增
        dialogFormVisible(){
            this.visible = true;
            this.title = "新增公告"
        },
        handleSelectionChange(selection) {
          this.selectedRow = selection
        },
        // 编辑
        handleEdit(index, row) {
          this.visible = true
          this.title = '编辑公告'
          this.updateTableData = row
        },
        //删除
        handleDelete(index, row) {
          this.tableData.splice(index,1)
          api.noticeDelete(row.id).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                this.$message.success('删除成功')
              }else{
                this.$message.error(res.data.message)
              }
          })
        },
        //作废
        handleCancel(index, row){
            row.status = 2
            // 提交表单数据
            api.noticeAdd(row).then(res =>{
                if(res.type === 'error'){
                    this.$message.error(res.message)
                }else if(res.data.code === 200){
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  //重新获取数据
                  this.onSubmit();
                }else{
                  this.$message.error(res.data.message)
                }
            })
        },
        //批量删除
        batchDelete(){
          var deleteIds = '';
          console.log(this.selectedRow)
          this.selectedRow.map(item =>{
            const index = this.tableData.findIndex((data) => data.id === item.id);
            this.tableData.splice(index,1)
            if(deleteIds === ''){
              deleteIds = item.id
            }else{
              deleteIds = deleteIds + "," + item.id
            }
          })
          if(deleteIds === ''){
            this.$message.error("请勾选删除项")
            return;
          }
          api.noticeDelete(deleteIds).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                console.log('删除成功');
              }else{
                this.$message.error(res.data.message)
              }
          })
        },        
        getStatusText(status){
            switch(status){
              case 0 : return '待发布';
              case 1 : return '已发布';
              case 2 : return '作废';
              default : return '';
            }
        },
        filterTag(value, row) {
          return row.status === value;
        },
        getReceivers() {
            return new Promise((resolve, reject) => {
              api.buildListAll().then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                  reject(res.message);
                } else if (res.data.code === 200) {
                  const tableData = res.data.data.buildInfos;
                  this.options = tableData.map(item => ({
                    value: item.id,
                    label: item.buildingName + "-" + item.unit
                  }));
                  resolve();
                } else {
                  this.$message.error(res.data.message);
                  reject(res.data.message);
                }
              });
            });
        },
        // 初始化FormData
        handleUpdateData(newData){
            this.updateTableData = newData
        }
      },
      created(){
        this.getReceivers().then(() => {
          this.onSubmit(); // 确保 receivers 解析时 options 已加载
        });
      }
  }
  </script>
  
  <style>
.notice .search{
  background-color: #fff;
  padding: 10px;
}
.notice .do{
  background-color: #fff;
  padding: 10px;
}
  </style>